/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.oraclefmw.weibo.impl;

import com.oraclefmw.weibo.WeiboPersist;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.List;
import weibo4j.User;

/**
 *
 * @author gniu
 */
public class WeiboPersistDBImpl implements WeiboPersist {
   
    private static final String JDBC_URL = "jdbc:oracle:thin:@localhost:1521:orcl";
    private static final String JDBC_USERNAME = "hr";
    private static final String JDBC_PASSWORD = "hr";
    
    public void persistUsers( List<User> users, boolean isFollower ) throws Exception
     {

        DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
        Connection conn = DriverManager.getConnection( JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
        Statement stmt = conn.createStatement();
        
        conn.setAutoCommit( false );
        
        for ( User u:users ) {
            
            StringBuilder sql = new StringBuilder();
            sql.append( "insert into wb_user(id, favourites_count, followers_count, friends_count, statuses_count, location,screen_name, is_verified, is_follower) values(").append( u.getId())
                    .append( ",")
                    .append( u.getFavouritesCount())
                    .append( ",")
                    .append( u.getFollowersCount())
                    .append( ",")
                    .append( u.getFriendsCount())
                    .append( ",")
                    .append( u.getStatusesCount())
                    .append( ",'")
                    .append( u.getLocation())
                    .append( "','")
                    .append( u.getScreenName())
                    .append( "','")
                    .append( u.isVerified() ? "Y" : "N")
                    .append(  "','")
                    .append(  isFollower ? "Y" : "N")
                    .append( "')");
            
            System.out.println( sql );
            stmt.addBatch( sql.toString() );
        }
        
        stmt.executeBatch();
        
        conn.commit();
        stmt.close();
        conn.close();
    }
}
